﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.Linq;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using Dropthings.Widget.Framework;
using Dropthings.Widget.Widgets;
using Dropthings.Widget.Widgets.FusionCharts;
using InfoSoftGlobal;
using Dropthings.Util;
using Dropthings.Business.Facade;
using Dropthings.Business.Facade.Context;
using System.Collections.Generic;
using System.Text;

public partial class FusionChart_ECMoney : System.Web.UI.UserControl, IWidget
{
    #region Fields

    private IWidgetHost _Host;
    private XElement _State;
    private XElement State
    {
        get
        {
            if (_State == null)
            {
                string stateXml = this._Host.GetState();
                if (string.IsNullOrEmpty(stateXml))
                {
                    _State = new XElement("state",
                        new XElement("year", DateTime.Now.Year.ToString()),
                        new XElement("orgnaziationCode", ""));
                }
                else
                {
                    _State = XElement.Parse(stateXml);
                }
            }
            return _State;
        }
    }

    public int ShowYear
    {
        get { return State.Element("year") == null ? DateTime.Now.Year : int.Parse(State.Element("year").Value); }
        set
        {
            if (State.Element("year") == null)
                State.Add(new XElement("year", value));
            else
                State.Element("year").Value = value.ToString();
        }
    }

    public string ShowBuildingCode
    {
        get { return State.Element("orgnaziationCode") == null ? "" : State.Element("orgnaziationCode").Value; }
        set
        {
            if (State.Element("orgnaziationCode") == null)
                State.Add(new XElement("orgnaziationCode", value));
            else
                State.Element("orgnaziationCode").Value = value;
        }
    }

    private string _chartSwfUrl = "";
    private StringBuilder _charXmlData = new StringBuilder();

    enum EcType
    {
        电=0,
        水=1,
        气=2
    }

    #endregion Fields

    #region IWidget接口实现
    void IEventListener.AcceptEvent(object sender, EventArgs e)
    {
        
    }

    void IWidget.Closed()
    {
    }

    void IWidget.Collasped()
    {
    }

    void IWidget.Expanded()
    {
    }

    void IWidget.HideSettings(bool userClicked)
    {
        SettingsPanel.Visible = false;
        if (userClicked)
        {
            this.ShowYear = int.Parse(YearDropDownList.SelectedValue);
            this.ShowBuildingCode = BuildingDropDownList.SelectedValue;
            this.SaveState();
            if (yearlbl.Text != ShowYear.ToString() || buildinglbl.Text != ShowBuildingCode)
            {
                if (lbtnBack.Visible)
                    CreateYearChartByMonth(typelbl.Text);
                else
                    CreateYearChart();
            }
            yearlbl.Text = ShowYear.ToString();
            buildinglbl.Text = ShowBuildingCode;
        }
        this.SaveState();
    }

    void IWidget.Init(IWidgetHost host)
    {
        this._Host = host;
    }

    void IWidget.Maximized()
    {
    }

    void IWidget.Restored()
    {
    }

    void IWidget.ShowSettings(bool userClicked)
    {
        SettingsPanel.Visible = true;
        if (userClicked)
        {
            YearDropDownList.SelectedIndex = -1;
            YearDropDownList.Items.FindByText(this.ShowYear.ToString()).Selected = true;
            BuildingDropDownList.SelectedIndex = -1;
            if (BuildingDropDownList.Items != null && BuildingDropDownList.Items.FindByValue(this.ShowBuildingCode) != null)
                BuildingDropDownList.Items.FindByValue(this.ShowBuildingCode).Selected = true;
        }
    }
    #endregion

    #region 页面事件处理
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (BuildingDropDownList.Items.Count == 0)
        {
            Dictionary<string, string> allBuildings = getAllBuildings();
            foreach (string key in allBuildings.Keys)
            {
                ListItem item = new ListItem();
                item.Text = allBuildings[key];
                item.Value = key;
                BuildingDropDownList.Items.Add(item);
            }
            if (BuildingDropDownList.Items.Count > 0)
            {
                this.ShowBuildingCode = BuildingDropDownList.Items[0].Value;
                buildinglbl.Text = this.ShowBuildingCode;
            }
        }

        if (YearDropDownList.Items.Count == 0)
        {
            for (int i = 2000; i <= DateTime.Now.Year; i++)
            {
                YearDropDownList.Items.Add(new ListItem(i.ToString()));
            }
        }
        if (!ScriptManager.GetCurrent(Page).IsInAsyncPostBack)
        {
            yearlbl.Text = this.ShowYear.ToString();
            if (!string.IsNullOrEmpty(this.ShowBuildingCode))
                buildinglbl.Text = this.ShowBuildingCode;
            CreateYearChart();
        }
        else
        {
            String sEventArguments = Request["__EVENTARGUMENT"];
            if (sEventArguments != null)
            {
                //extract arguments passed to the HTTP Request  
                Int32 iDelimiter = sEventArguments.IndexOf('$');
                String sArgument = sEventArguments.Substring(iDelimiter + 1);
                // extract the name of the post back function 
                if (sEventArguments.StartsWith(this._Host.ID.ToString()))
                {
                    // call the post back function passing the argument(s)
                    CreateYearChartByMonth(sArgument);
                }
                else
                {
                    if (string.IsNullOrEmpty(Literal1.Text))
                        CreateYearChart();
                }
            }
        }
    }

    protected void SaveSettings_Click(object sender, EventArgs e)
    {
        _Host.HideSettings(true);
    }

    protected void lbtnBack_Click(object sender, EventArgs e)
    {
        lbtnBack.Visible = false;
        CreateYearChart();
    }
    
    #endregion

    #region 页面处理方法
    private void ShowChart()
    {
         Literal1.Text = FusionCharts.RenderChartHTML(_chartSwfUrl, "", _charXmlData.ToString(), "myFirst", "100%", "267", false, false);
         _Host.Refresh(this);
    }

    private void SaveState()
    {
        var xml = this.State.Xml();
        this._Host.SaveState(xml);
        this._State = null;
    }

    private void CreateYearChart()
    {
        _charXmlData = new StringBuilder();
        _chartSwfUrl = "../FusionCharts/Pie3D.swf";
        _charXmlData.AppendFormat("<chart caption='能源年费用图 - {0} ({1})' unescapeLinks='0' animation='1' baseFontColor='FFFFFF' bgColor='2E4A89, 90B1DE' pieYScale='30'  pieSliceDepth='8' smartLineColor='FFFFFF'>", ShowYear, BuildingDropDownList.Items.FindByValue(buildinglbl.Text).Text);
        Dictionary<EcType, double> datas = getTotalMoneyInYear(ShowBuildingCode, ShowYear);
        foreach (EcType key in datas.Keys)
        {
            double money = datas[key];
            _charXmlData.AppendFormat("<set value='{0}' label='{1}' link='JavaScript:updateChart(%26quot;{2}%26quot;,%26quot;{3}%26quot;)' />", money, key, this._Host.ID, key);
        }
        _charXmlData.Append("<styles>");
        _charXmlData.Append("<definition>");
        _charXmlData.Append("<style name='CaptionFont' type='FONT' size='12' bold='1' />");
        _charXmlData.Append("<style name='LabelFont' type='FONT' color='2E4A89' bgColor='FFFFFF' bold='1' />");
        _charXmlData.Append("<style name='ToolTipFont' type='FONT' bgColor='2E4A89' borderColor='2E4A89' />");
        _charXmlData.Append("</definition>");
        _charXmlData.Append("<application>");
        _charXmlData.Append("<apply toObject='CAPTION' styles='CaptionFont' />");
        _charXmlData.Append("<apply toObject='DATALABELS' styles='LabelFont' />");
        _charXmlData.Append("<apply toObject='TOOLTIP' styles='ToolTIpFont' />");
        _charXmlData.Append("</application>");
        _charXmlData.Append("</styles>");
        _charXmlData.Append("</chart>");
        ShowChart();
    }

    private void CreateYearChartByMonth(string propertyType)
    {
         lbtnBack.Visible = true;
         typelbl.Text = propertyType;
        _charXmlData = new StringBuilder();
        _chartSwfUrl = "../FusionCharts/Column2D.swf";
        _charXmlData.AppendFormat("<chart caption='{0}能源月花费图- {1} ({2})' xAxisName='月份' yAxisName='元' showNames='1' ", propertyType, ShowYear, BuildingDropDownList.Items.FindByValue(this.ShowBuildingCode).Text);
        _charXmlData.Append("animation='1' baseFontColor='666666' useRoundEdges='1'>");
        
        DataSet datasDS = getYearDatasByECType(ShowYear, propertyType);
        DataTable dt = null;
        //_charXmlData.AppendFormat("<dataset seriesName=''>");
        if (datasDS != null && datasDS.Tables != null && datasDS.Tables.Count > 0)
        {
            dt = datasDS.Tables[0];
        }
        for (int i = 1; i <= 12; i++)
        {
            string strData = string.Format("<set label='{0}' value='' />",i);
            if (dt != null)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    if (Convert.ToInt32(dr["ReadingMonth"]) == i)
                    {
                        strData = string.Format("<set label='{0}' value='{1}' />", i,Convert.ToDouble(dr["Moneys"]));
                        break;
                    }
                }
            }
            _charXmlData.Append(strData);
        }
        //_charXmlData.Append("</dataset>");  
        _charXmlData.Append("</chart>");
        ShowChart();
    }

   
    #endregion

    private Dictionary<string, string> getAllBuildings()
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            Dictionary<string, string> allBuildings = new Dictionary<string, string>();
            DataSet ds = facade.GetOrganizeBaseInfo();
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    string name = Convert.ToString(dr["OrganizeName"]);
                    string key = Convert.ToString(dr["OrganizeIdentify"]);
                    allBuildings.Add(key, name);
                }
            }
            return allBuildings;
        }
    }

    private string getOrganizePorpertyName(string propertyCode)
    {
        string PorpertyName = string.Empty;
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            DataSet ds = facade.GetOrganizePeropertyInfo(propertyCode);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                PorpertyName = ds.Tables[0].Rows[0]["OrgPropertyName"].ToString();
            }
        }
        return PorpertyName;
    }

    private DataSet getAmmeterItemInfo()
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            DataSet ds = facade.GetAmmeterItemInfo();
            return ds;
        }
    }

    
    private Dictionary<EcType, double> getTotalMoneyInYear(string ShowBuildingCode, int year)
    {
        Dictionary<EcType, double> values = new Dictionary<EcType, double>();
        values.Add(EcType.电, getAmmeterTotalMoneyInYear(ShowBuildingCode, year));
        values.Add(EcType.水, getWaterTotalMoneyInYear(ShowBuildingCode, year));
        values.Add(EcType.气, getGasTotalMoneyInYear(ShowBuildingCode, year));
        return values;
    }
    private double getAmmeterTotalMoneyInYear(string ShowBuildingCode,int year)
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            double moneys=0;
            DataSet ds = facade.GetAmmeterTotalMoneyInYear(ShowBuildingCode,year);
            if(ds!=null && ds.Tables!=null && ds.Tables.Count>0 && ds.Tables[0].Rows.Count > 0)
                moneys = Convert.ToDouble(ds.Tables[0].Rows[0]["Moneys"]);
            return moneys;
        }
    }
    private double getWaterTotalMoneyInYear(string ShowBuildingCode, int year)
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            double moneys = 0;
            DataSet ds = facade.GetWaterTotalMoneyInYear(ShowBuildingCode, year);
            if (ds != null && ds.Tables != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                moneys = Convert.ToDouble(ds.Tables[0].Rows[0]["Moneys"]);
            return moneys;
        }
    }
    private double getGasTotalMoneyInYear(string ShowBuildingCode, int year)
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            double moneys = 0;
            DataSet ds = facade.GetGasTotalMoneyInYear(ShowBuildingCode, year);
            if (ds != null && ds.Tables != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                moneys = Convert.ToDouble(ds.Tables[0].Rows[0]["Moneys"]);
            return moneys;
        }
    }
    
    private DataSet getYearDatasByECType(int year,string value)
    {
        DataSet ds=null;
        EcType type=(EcType)Enum.Parse(typeof(EcType),value,true);
        switch (type)
        {
            case EcType.电: ds = GetAmmeterMonthMoneyInYear(this.ShowBuildingCode, year); break;
            case EcType.水: ds = GetWaterMonthMoneyInYear(this.ShowBuildingCode, year); break;
            case EcType.气: ds = GetGasMonthMoneyInYear(this.ShowBuildingCode, year); break;
        }
        return ds;
    }
    private DataSet GetAmmeterMonthMoneyInYear(string ShowBuildingCode, int year)
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            DataSet ds = facade.GetAmmeterMonthMoneyInYear(ShowBuildingCode, year);
            return ds;
        }
    }
    private DataSet GetWaterMonthMoneyInYear(string ShowBuildingCode, int year)
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            DataSet ds = facade.GetWaterMonthMoneyInYear(ShowBuildingCode, year);
            return ds;
        }
    }
    private DataSet GetGasMonthMoneyInYear(string ShowBuildingCode, int year)
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            DataSet ds = facade.GetGasMonthMoneyInYear(ShowBuildingCode, year);
            return ds;
        }
    }
    private DataSet getYearDatasByProperty(int year, string propertyCode)
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            DataSet ds = facade.GetAmmeterYearDatasByProperty(year, propertyCode);
            return ds;
        }
    }
}